package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.domain.MessageSms;
import cn.itsource.ymcc.dto.CourseDocumentDto;
import cn.itsource.ymcc.service.IMessageSmsService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import static java.lang.String.format;

@RocketMQMessageListener(consumerGroup = "consumer-course-sms-group",
        topic = "course-topic",
        selectorExpression = "*",
        messageModel = MessageModel.CLUSTERING
)
@Slf4j
@Component
public class CourseMQSMSListener implements RocketMQListener<MessageExt> {

    @Value("${sendmessage.sms-message}")
    private String smsMessage ;

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            String mess = new String(messageExt.getBody(),"utf-8");
            CourseDocumentDto courseDocumentDto = JSON.parseObject(mess, CourseDocumentDto.class);
            //发送 短信
            // 1. 构造消息
            String smsMsg = format(smsMessage, courseDocumentDto.getId(), courseDocumentDto.getName());
            // 2. 查询用户手机号 封装mes对象
            MessageSms sms = new MessageSms();
            sms.setTitle("课程发布");
            sms.setContent(smsMsg);
            sms.setSendTime(new Date());
            sms.setUserId(1L);

            // 发送
            log.info("发送短信：{}",sms.getContent());

            messageSmsService.insert(sms);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
